package syntaxcolor.v4.syntaxcolor.rule;

import org.eclipse.swt.custom.StyleRange;

import syntaxcolor.v4.syntaxcolor.scanner.Scanner;
import syntaxcolor.v4.syntaxcolor.token.Token;

/**
 * 多行着色规则，继承自PatternRule，也就是指定开始字符和结束字符的字符串，换行符不是终止字符
 * 
 * @author wyl
 */
public class MultiLineRule extends PatternRule {

  private String exceptStart = null;

  public MultiLineRule(String name, String startStr, String endStr,
      StyleRange style) {
    super(name, startStr, new String[] { endStr }, '\0', style);
  }

  /**
   * 增加一个例外字符，也就是虽然开头符合起始字符，但如果起始字符后是指定的字符的话，就不认为符合此规则
   * 例子就是JavaDoc的开始字符[/**结束斜杠(这里不能写/是因为写了注释就结束了)]:
   * 虽然符合多行注释的开始字符/**,但后续是/的时候就不再符合JavaDoc注释规则.而是符合多行注释规则
   * 
   * @param name
   * @param startStr
   * @param endStr
   * @param style
   * @param exceptStart
   */
  public MultiLineRule(String name, String startStr, String endStr,
      StyleRange style, String exceptStart) {
    this(name, startStr, endStr, style);
    this.exceptStart = exceptStart;
  }

  /*
   * (non-Javadoc)
   * @seesyntaxcolor.v3.syntaxcolor.rules.PatternRule#evaluate(syntaxcolor.v3.
   * syntaxcolor.Scanner)
   */
  @Override
  public Token evaluate(Scanner scanner) {
    Token t = super.evaluate(scanner);
    if (t == null || this.exceptStart == null) {
      return t;
    }
    int offset = scanner.getOffset();
    scanner.setOffset(t.getOffset());
    int startIndex = 0;
    int ch = scanner.read();
    while (startIndex < exceptStart.length()
        && ch == exceptStart.charAt(startIndex)) {
      ch = scanner.read();
      startIndex++;
    }
    if (startIndex == exceptStart.length()) {
      scanner.setOffset(t.getOffset());
      return null;
    }
    scanner.setOffset(offset);
    return t;
  }

}
